#include "SD.h"
#define SD_DUMMY_BYTE 0xff
#define SD_CS_PIN GPIO_Pin_11
#define SD_CS_GPIO_PORT GPIOC
#define SD_CS_HIGH do{SD_CS_GPIO_PORT->ODR|=SD_CS_PIN;}while(0)
#define SD_CS_LOW do{SD_CS_GPIO_PORT->ODR&=~SD_CS_PIN;}while(0)


// PC13 as the CS-Pin
void SPIx_Init(){
	SPI_InitTypeDef SPI_InitStruct;
	SPI_InitStruct.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_4; // 84/4-->21Mhz
	SPI_InitStruct.SPI_CPHA = SPI_CPHA_2Edge;
	SPI_InitStruct.SPI_CPOL = SPI_CPOL_High;
	SPI_InitStruct.SPI_CRCPolynomial = 7;
	SPI_InitStruct.SPI_DataSize = SPI_DataSize_8b;
	SPI_InitStruct.SPI_Direction = SPI_Direction_2Lines_FullDuplex;
	SPI_InitStruct.SPI_FirstBit = SPI_FirstBit_MSB;
	SPI_InitStruct.SPI_Mode = SPI_Mode_Master;
	SPI_InitStruct.SPI_NSS = SPI_NSS_Soft; // Manual Chip-Select
	
	SPI_Init(SPI3,&SPI_InitStruct);
	SPI_Cmd(SPI3,ENABLE);
}


void SD_IO_Init(void)
{
  GPIO_InitTypeDef  GPIO_InitStruct;
  uint8_t counter;

  /* Configure SD_CS_PIN pin: SD Card CS pin */
  GPIO_InitStruct.GPIO_Pin = SD_CS_PIN;
  GPIO_InitStruct.GPIO_Mode = GPIO_Mode_OUT;
  GPIO_InitStruct.GPIO_PuPd = GPIO_PuPd_UP;
  GPIO_InitStruct.GPIO_OType = GPIO_OType_PP;
  GPIO_InitStruct.GPIO_Speed = GPIO_Speed_100MHz;
  GPIO_Init(SD_CS_GPIO_PORT, &GPIO_InitStruct);

  /*------------Put SD in SPI mode--------------*/
  /* SD SPI Config */
  SPIx_Init();
  
  /* SD chip select high */
  SD_CS_HIGH;
  
  /* Send dummy byte 0xFF, 10 times with CS high */
  /* Rise CS and MOSI for 80 clocks cycles */
  for (counter = 0; counter <= 9; counter++)
  {
    /* Send dummy byte 0xFF */
    SD_IO_WriteByte(SD_DUMMY_BYTE);
  }
}

/**
  * @brief Set the SD_CS pin.
  * @param val: pin value.
  */
void SD_IO_CSState(uint8_t val)
{
  if(val) SD_CS_HIGH;
  else SD_CS_LOW;
}

void SPI_WRData(uint8_t* DataIn, uint8_t* DataOut)
{
  /* Send the byte */
  while(SPI_GetFlagStatus(SPI3,SPI_FLAG_TXE)!=SET);
  SPI_SendData(SPI3,*DataOut);
  while(SPI_GetFlagStatus(SPI3,SPI_FLAG_RXNE)!=SET);
  *DataIn = SPI_ReceiveData(SPI3);
}

uint8_t SD_IO_WriteByte(uint8_t Data)
{
  uint8_t tmp;
  /* Send the byte */
  SPI_WRData(&tmp,&Data);
  return tmp;
}

void SD_IO_WriteReadData(uint8_t *DataIn, uint8_t *DataOut, uint16_t DataLength){
  for(int i=0;i<DataLength;i++){
	  SPI_WRData(DataIn+i,DataOut);
  }
}



